package gaml.text.parser;

import gaml.error.GamlException;
import gaml.text.YamlText;
import gaml.text.YamlTextParser;
import gaml.yaml.ScalarNode;
import gaml.yaml.YamlNode;
import gaml.yaml.ahchor.YamlAnchorCodeStore;


/**
 * get scalar node from it's text representaion
 * @author shnireck
 *
 */
public class ScalarNodeParser implements YamlTextParser {
	static final String incorrectLineFormat = "Mailformed scalar node line [%s]";

	YamlAnchorCodeStore anchors = null;

	public ScalarNodeParser (YamlAnchorCodeStore store) { this.anchors = store; }

	@Override
	public boolean isParserFor (YamlText text) throws GamlException { return text.getValue ().startsWith (">"); }

	@Override
	public String getParsingTail (YamlText text) throws GamlException { return text.getValue ().substring (1).trim(); }

	@Override
	public YamlNode parseText (YamlText text, YamlNode parent) throws GamlException {
		ScalarNode node = (ScalarNode) new ScalarNode (parent).setTag (text.getTag ());
		node.setAnchor (anchors.getAnchor (text.getAnchor (), node));
		
		StringBuilder value = new StringBuilder ();
		
		if (isParserFor (text)) value.append (getParsingTail (text));
		else throw new GamlException (String.format (incorrectLineFormat, text.getValue ()));
		
		while (! text.next ().isEnd ()) {
			if (text.getValue ().isEmpty ()) value.append (text.getLineBreak ());
			else if (text.getIdentation () != (node.getLevel () + 1)) break;
			else value.append (text.getLineBreak ()).append (text.getValue ().trim ());
		}
		
		node.setValue (value.toString ().trim ());
		return node;
	}
}